const initVips = async () => {
  const DISCOUNT = {
    '1': 100,
    '3': 90,
    '6': 80,
    '12': 70
  }
  const _getMonthPrice = (price, months) => {
    const discount = DISCOUNT[months]
    return Math.round(price * discount / 100) * months
  }
  const circles = await new Parse.Query('RcCircle').doesNotExist('vipPrice').limit(10000).find()
  const tasks = []
  circles.forEach((circle) => {
    circle.set('vipPrice', 10)
    const vips = Object.keys(DISCOUNT).map(months => {
      return new Parse.Object('RcVip', {
        circle,
        months: +months,
        discount: DISCOUNT[months],
        price: _getMonthPrice(10, +months)
      })
    })
    tasks.push(circle, ...vips)
  })
  await Parse.Object.saveAll(tasks)
}

const initPictures = async () => {
  const resources = await new Parse.Query('RcResource').doesNotExist('pictures').limit(10000).find()
  const tasks = []
  resources.forEach(item => {
    const image = item.get('image')
    if (image) {
      item.set('pictures', [image])
      tasks.push(item)
    }
  })
  await Parse.Object.saveAll(tasks)
}

const initResourceType = async () => {
  const resources = await new Parse.Query('RcResource').doesNotExist('type').limit(100000).find()
  resources.forEach(item => {
    const price = item.get('price')
    if (price) {
      item.set('type', 0)
    } else {
      item.set('type', 1)
    }
  })
}
Parse.Cloud.job('initFieldForV1.1', async (req, status) => {
  await initVips()
  await initPictures()
  await initResourceType()
  status.success()
})

